package com.shyroke.daydayzhuansvc.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/1/14 17:52
 */
@Component
public class OSSClientUtils {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;


    private OSS ossClient;

    public OSSClientUtils(){

        this.endpoint = OSSClientConstants.ENDPOINT;
        this.accessKeyId = OSSClientConstants.ACCESS_KEY_ID;
        this.accessKeySecret = OSSClientConstants.ACCESS_KEY_SECRET;
        this.bucketName = OSSClientConstants.BUCKET_NAME;
        ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
    }


    public void uploadImg(InputStream inputStream,String path) {
        ossClient.putObject(bucketName,path,inputStream);
    }


    public String getImgUrl(String path) {

        //设置过期时间十分钟
        Date expiration = new Date(new Date().getTime()+600*1000);

       URL url =  ossClient.generatePresignedUrl(this.bucketName,path,expiration);

       String src = url.toString();

       if(!StringUtils.isEmpty(src)){
           src = src.replaceFirst("http","https");
       }

        if(src.contains("?")){
            //取出图片地址的参数,防止过期。
            src = src.substring(0,src.indexOf("?"));
        }

        return src;
    }

    public URL getImgURL(String path) {

        //设置过期时间十分钟
        Date expiration = new Date(new Date().getTime()+600*1000);

        return ossClient.generatePresignedUrl(this.bucketName,path,expiration);

    }

    public void deleteImg(String bucketName, String path) {
        ossClient.deleteObject(bucketName,path);
    }

    public InputStream getFileObj(String bucketName,String sitemapPath) {
        return ossClient.getObject(bucketName,sitemapPath).getObjectContent();
    }
}
